package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     *新增菜品,同时保存对应的口味数据
     */
    @Transactional//因为要对两张表的数据进行保存,所以要开启事务管理,并在启动类上添加注解
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保留菜品的基本信息
        this.save(dishDto);
        //设置菜品与口味的关系
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(flavor->flavor.setDishId(dishDto.getId()));
        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询 diah 基本信息,在 Dish 表查
        Dish dish = this.getById(id);

        DishDto dishDto=new DishDto();
        //查询当前菜品对应的口味信息，从 dish_flavor表查询
        QueryWrapper<DishFlavor> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dish_id",dish.getId());
        List<DishFlavor> dishFlavorsList= dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(dishFlavorsList);

        //将菜品与口味信息封装到 Dto中
        BeanUtils.copyProperties(dish,dishDto);

        return dishDto;
    }

    /**
     * 更新菜品信息，同时更新对应的口味信息
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto){
        //更新 dish表基本信息
        this.updateById(dishDto);

        //清理当前菜品对应口味数据---dish_flavor表的delete操作
        QueryWrapper<DishFlavor> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("dish_id",dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //添加当前提交过来的口味数据---dish_flavor表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(flavor->flavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }
}
